#!/usr/bin/env python3
"""
面向 java-17-openjdk 软件的 MCP Server

MCP tools 列表：
- keytool_help: 显示 keytool 命令的帮助信息
- keytool_genkeypair: 生成密钥对并创建密钥库文件
- keytool_list: 查看密钥库中的内容
- keytool_exportcert: 从密钥库中导出证书
- keytool_delete: 删除密钥库中的条目
- keytool_importcert: 导入证书到密钥库
- keytool_printcert: 打印证书内容
- javadoc_help: 显示 javadoc 命令的帮助信息
- javadoc_generate: 生成 Java 文档

所有工具返回统一的 JSON 结构：
{
  "success": bool,
  "command": str,
  "exit_code": int,
  "stdout": str,
  "stderr": str
}
"""

import subprocess
import json
from typing import List, Optional
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("Java-17-OpenJDK MCP Server")

@mcp.tool()
def keytool_help() -> dict:
    """
    显示 keytool 命令的帮助信息
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    try:
        result = subprocess.run(
            ["keytool", "--help"],
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": "keytool --help",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": "keytool --help",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def keytool_genkeypair(alias: str, keyalg: str = "RSA", keysize: int = 2048, 
                      keystore: str = "mykeystore.jks", storepass: Optional[str] = None,
                      validity: int = 90) -> dict:
    """
    生成密钥对并创建密钥库文件
    
    参数:
        alias: 密钥别名
        keyalg: 密钥算法，默认为 RSA
        keysize: 密钥大小，默认为 2048
        keystore: 密钥库文件名，默认为 mykeystore.jks
        storepass: 密钥库密码（可选）
        validity: 证书有效期（天数），默认为 90
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = ["keytool", "-genkeypair", "-alias", alias, "-keyalg", keyalg, 
           "-keysize", str(keysize), "-keystore", keystore, "-validity", str(validity)]
    
    if storepass:
        cmd.extend(["-storepass", storepass])
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=60,
            input="\n".join(["", "", "", "", "", "", "", "yes"]) if not storepass else None
        )
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def keytool_list(keystore: str, storepass: Optional[str] = None) -> dict:
    """
    查看密钥库中的内容
    
    参数:
        keystore: 密钥库文件名
        storepass: 密钥库密码（可选）
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = ["keytool", "-list", "-keystore", keystore]
    
    if storepass:
        cmd.extend(["-storepass", storepass])
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30,
            input=f"{storepass}\n" if not storepass else None
        )
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def keytool_exportcert(alias: str, keystore: str, storepass: str, output_file: str) -> dict:
    """
    从密钥库中导出证书
    
    参数:
        alias: 密钥别名
        keystore: 密钥库文件名
        storepass: 密钥库密码
        output_file: 输出证书文件名
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = ["keytool", "-exportcert", "-alias", alias, "-keystore", keystore, 
           "-file", output_file, "-storepass", storepass]
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def keytool_delete(alias: str, keystore: str, storepass: str) -> dict:
    """
    删除密钥库中的条目
    
    参数:
        alias: 要删除的密钥别名
        keystore: 密钥库文件名
        storepass: 密钥库密码
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = ["keytool", "-delete", "-alias", alias, "-keystore", keystore, "-storepass", storepass]
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def keytool_importcert(alias: str, cert_file: str, keystore: str, storepass: str) -> dict:
    """
    导入证书到密钥库
    
    参数:
        alias: 证书别名
        cert_file: 证书文件名
        keystore: 密钥库文件名
        storepass: 密钥库密码
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = ["keytool", "-importcert", "-alias", alias, "-file", cert_file, 
           "-keystore", keystore, "-storepass", storepass]
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30,
            input="yes\n"
        )
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def keytool_printcert(cert_file: str) -> dict:
    """
    打印证书内容
    
    参数:
        cert_file: 证书文件名
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = ["keytool", "-printcert", "-file", cert_file]
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def javadoc_help() -> dict:
    """
    显示 javadoc 命令的帮助信息
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    try:
        result = subprocess.run(
            ["javadoc", "-help"],
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": "javadoc -help",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": "javadoc -help",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def javadoc_generate(java_file: str, access_level: str = "public", output_dir: str = "docs") -> dict:
    """
    生成 Java 文档
    
    参数:
        java_file: Java 源文件名
        access_level: 访问级别（public/protected/private/package），默认为 public
        output_dir: 输出目录，默认为 docs
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = ["javadoc", f"-{access_level}", java_file, "-d", output_dir]
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=60
        )
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()